package tt.dz.biz.service.account;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tt.dz.biz.dao.account.AccountingDAO;
import tt.dz.biz.service.common.CommonService;
import tt.dz.common.LogUtil;
import tt.dz.common.SMSMessageUtil;
import tt.dz.vo.TranInfoVO;

@Service("dividendMonitorService")
public class DividendMonitorService
{
  @Resource(name="accountingRuleDAO")
  protected AccountingDAO accountingDAO;
  @Resource(name="commonService")
  protected CommonService commonService;
  @Value("dividend.decide.time")
  private static int dividendMin;
  @Value("${monitor.traninfo.indays}")
  private static int spanDay;
  @Value("${monitor.mobile}")
  private String mobileNos;
  @Value("${dividend.monitor.msg}")
  private String message;
  
  public void init()
  {
    if (dividendMin == 0) {
      dividendMin = 30;
    }
    if (spanDay == 0) {
      spanDay = 30;
    }
    spanDay = 0 - spanDay;
  }
  
  public void monitorTranInfoState()
  {
    try
    {
      List<TranInfoVO> overTimeList = new ArrayList();
      Calendar carlendar = Calendar.getInstance();
      carlendar.setTime(this.commonService.getAccountingDate());
      carlendar.add(5, spanDay);
      List<TranInfoVO> tranList = this.accountingDAO.queryTranInfoForMonitor(carlendar.getTime());
      Date now = new Date();
      long rs = 0L;
      if (!CollectionUtils.isEmpty(tranList)) {
        for (TranInfoVO tranInfoVO : tranList)
        {
          rs = (now.getTime() - tranInfoVO.getPlatTime().getTime()) / 60000L;
          if (rs > dividendMin) {
            overTimeList.add(tranInfoVO);
          }
        }
      }
      if (CollectionUtils.isEmpty(overTimeList)) {
        return;
      }
      sendMonitorMsg();
    }
    catch (Exception e)
    {
      LogUtil.error("交易是否记录分录的监控服务异常", e);
    }
  }
  
  public void sendMonitorMsg()
  {
    try
    {
      if (StringUtils.isNotBlank(this.mobileNos))
      {
        String[] mobiles = this.mobileNos.split(",");
        for (String mobile : mobiles) {
          SMSMessageUtil.sendMessage(mobile, this.message);
        }
      }
    }
    catch (Exception e)
    {
      LogUtil.error("监控短信发送失败", e);
    }
  }
}
